package io.gitee.archx.sc.web.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * ConsumerController
 *
 * @author Archx[archx@foxmail.com]
 * at 2018/7/24 21:50
 */
@RestController
@RequestMapping("/consume")
public class ConsumerController {

    private RestTemplate restTemplate;

    private LoadBalancerClient loadBalancerClient;

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Autowired
    public void setLoadBalancerClient(LoadBalancerClient loadBalancerClient) {
        this.loadBalancerClient = loadBalancerClient;
    }

    @GetMapping("/{name}")
    @HystrixCommand(fallbackMethod = "fallback")
    public String consume(@PathVariable("name") String name) {
        return restTemplate.getForObject("http://spring-cloud-service-provider/hello/" + name, String.class);
    }

    @GetMapping("ribbon")
    public String ribbon() {
        ServiceInstance instance = loadBalancerClient.choose("spring-cloud-service-provider");
        return instance.getUri().toString();
    }

    public String fallback(String name) {
        return "Sorry! " + name;
    }
}
